# -*- coding: utf-8 -*-

from jira import JIRA
from jinja2 import Template,FileSystemLoader,Environment,select_autoescape
from collections import OrderedDict
import re
import sys 
import json
reload(sys)
sys.setdefaultencoding('utf-8')


projectName = 'HelloWorld'
personalObj = {}


def test(input):
    return input
# 统计个人最多最少数量
def personalSummary(assigneeName,issueCount):
    global personalObj
    if assigneeName not in personalObj:
        personalObj[assigneeName] = issueCount
    else:
        personalObj[assigneeName] = personalObj[assigneeName] + issueCount
    personalObj = OrderedDict(sorted(personalObj.items(), key=lambda x: x[1],reverse=True))

def sortedDictValues3(adict): 
    keys = adict.keys() 
    keys.sort() 
    return map(adict.get, keys)   

# 统计JIRA数量
def getSummary(jiraID):
    jira_URL = 'http://jira.jd.com'
    userName = ''
    password = ''
    jira = JIRA(basic_auth=(userName, password),options={'server': jira_URL})
    baseJQL = 'project=' + jiraID + ' AND issuetype=Bug'
    issues = jira.search_issues(baseJQL)
    assigneeList = []
    summaryList = {}
    jra = jira.project(jiraID)
    global projectName
    projectName = jra.name
    for issue in issues:
        assigneeName = (issue.raw['fields']['assignee']['displayName'])
        if assigneeName not in assigneeList:
            assigneeList.append(assigneeName)

    for assignee in assigneeList:
        extraJQL = "project=" + jiraID + " AND issuetype=Bug AND createdDate >= '2018-05-25' AND createdDate <= '2018-05-31' AND assignee="  + assignee
        assigneeObj = {}
        assignee_issues = jira.search_issues(extraJQL)
        assigneeObj['name'] = assignee
        assigneeObj['totalCount'] = len(assignee_issues)
        personalSummary(assignee,len(assignee_issues))
        issueObjList = []
        
        # 统计：功能遗漏
        function_miss_Obj = {}
        function_miss_Obj['type'] = '功能遗漏'.decode('utf-8')
        function_miss_Obj['Blocker'] = 0
        function_miss_Obj['Critical'] = 0
        function_miss_Obj['Major'] = 0
        function_miss_Obj['Minor'] = 0
        function_miss_Obj['Enhancement'] = 0

        # 统计: 程序逻辑错误
        system_logicError_Obj = {}
        system_logicError_Obj['type'] = '程序逻辑错误'.decode('utf-8')
        system_logicError_Obj['Blocker'] = 0
        system_logicError_Obj['Critical'] = 0
        system_logicError_Obj['Major'] = 0
        system_logicError_Obj['Minor'] = 0
        system_logicError_Obj['Enhancement'] = 0

        # 统计: 程序校验错误
        system_checkError_Obj = {}
        system_checkError_Obj['type'] = '程序校验错误'.decode('utf-8')
        system_checkError_Obj['Blocker'] = 0
        system_checkError_Obj['Critical'] = 0
        system_checkError_Obj['Major'] = 0
        system_checkError_Obj['Minor'] = 0
        system_checkError_Obj['Enhancement'] = 0

        # 统计: 界面错误
        uiError_Obj = {}
        uiError_Obj['type'] = '界面错误'.decode('utf-8')
        uiError_Obj['Blocker'] = 0
        uiError_Obj['Critical'] = 0
        uiError_Obj['Major'] = 0
        uiError_Obj['Minor'] = 0
        uiError_Obj['Enhancement'] = 0

        # 统计: 兼容错误
        compatibleError_Obj = {}
        compatibleError_Obj['type'] = '兼容错误'.decode('utf-8')
        compatibleError_Obj['Blocker'] = 0
        compatibleError_Obj['Critical'] = 0
        compatibleError_Obj['Major'] = 0
        compatibleError_Obj['Minor'] = 0
        compatibleError_Obj['Enhancement'] = 0

        # 统计: 用户体验问题/优化提升
        user_Obj = {}
        user_Obj['type'] = '用户体验问题/优化提升'.decode('utf-8')
        user_Obj['Blocker'] = 0
        user_Obj['Critical'] = 0
        user_Obj['Major'] = 0
        user_Obj['Minor'] = 0
        user_Obj['Enhancement'] = 0

        # 统计: 接口问题
        interface_Obj = {}
        interface_Obj['type'] = '接口问题'.decode('utf-8')
        interface_Obj['Blocker'] = 0
        interface_Obj['Critical'] = 0
        interface_Obj['Major'] = 0
        interface_Obj['Minor'] = 0
        interface_Obj['Enhancement'] = 0

        # 统计: 性能问题
        performance_Obj = {}
        performance_Obj['type'] = '性能问题'.decode('utf-8')
        performance_Obj['Blocker'] = 0
        performance_Obj['Critical'] = 0
        performance_Obj['Major'] = 0
        performance_Obj['Minor'] = 0
        performance_Obj['Enhancement'] = 0

        # 统计: 安全问题
        security_Obj = {}
        security_Obj['type'] = '安全问题'.decode('utf-8')
        security_Obj['Blocker'] = 0
        security_Obj['Critical'] = 0
        security_Obj['Major'] = 0
        security_Obj['Minor'] = 0
        security_Obj['Enhancement'] = 0

        # 统计: 环境问题
        environment_Obj = {}
        environment_Obj['type'] = '环境问题'.decode('utf-8')
        environment_Obj['Blocker'] = 0
        environment_Obj['Critical'] = 0
        environment_Obj['Major'] = 0
        environment_Obj['Minor'] = 0
        environment_Obj['Enhancement'] = 0

        for assignee_issue in assignee_issues:
            customObj = assignee_issue.raw['fields']['customfield_11400']
            if customObj is not None:
                typeDesc = customObj['value'].encode('utf-8')
                if typeDesc == '功能遗漏':
                    propertyObj = assignee_issue.raw['fields']['customfield_11401']
                    propertyDesc = propertyObj['value'].encode('utf-8')
                    if propertyDesc.find('Blocker') != -1:
                        function_miss_Obj['Blocker'] = int(function_miss_Obj['Blocker']) + 1
                    if propertyDesc.find('Major') != -1:
                        function_miss_Obj['Major'] = int(function_miss_Obj['Major']) + 1
                    if propertyDesc.find('Critical') != -1:
                        function_miss_Obj['Critical'] = int(function_miss_Obj['Critical']) + 1 
                    if propertyDesc.find('Enhancement') != -1:
                        function_miss_Obj['Enhancement'] = int(function_miss_Obj['Enhancement']) + 1 
                if typeDesc == '程序逻辑错误':
                    propertyObj = assignee_issue.raw['fields']['customfield_11401']
                    propertyDesc = propertyObj['value'].encode('utf-8')
                    if propertyDesc.find('Blocker') != -1:
                        system_logicError_Obj['Blocker'] = int(system_logicError_Obj['Blocker']) + 1
                    if propertyDesc.find('Major') != -1:
                        system_logicError_Obj['Major'] = int(system_logicError_Obj['Major']) + 1
                    if propertyDesc.find('Critical') != -1:
                        system_logicError_Obj['Critical'] = int(system_logicError_Obj['Critical']) + 1 
                    if propertyDesc.find('Enhancement') != -1:
                        system_logicError_Obj['Enhancement'] = int(system_logicError_Obj['Enhancement']) + 1
                if typeDesc == '程序校验错误':
                    propertyObj = assignee_issue.raw['fields']['customfield_11401']
                    propertyDesc = propertyObj['value'].encode('utf-8')
                    if propertyDesc.find('Blocker') != -1:
                        system_checkError_Obj['Blocker'] = int(system_checkError_Obj['Blocker']) + 1
                    if propertyDesc.find('Major') != -1:
                        system_checkError_Obj['Major'] = int(system_checkError_Obj['Major']) + 1
                    if propertyDesc.find('Critical') != -1:
                        system_checkError_Obj['Critical'] = int(system_checkError_Obj['Critical']) + 1 
                    if propertyDesc.find('Enhancement') != -1:
                        system_checkError_Obj['Enhancement'] = int(system_checkError_Obj['Enhancement']) + 1
                if typeDesc == '界面错误':
                    propertyObj = assignee_issue.raw['fields']['customfield_11401']
                    propertyDesc = propertyObj['value'].encode('utf-8')
                    if propertyDesc.find('Blocker') != -1:
                        uiError_Obj['Blocker'] = int(uiError_Obj['Blocker']) + 1
                    if propertyDesc.find('Major') != -1:
                        uiError_Obj['Major'] = int(uiError_Obj['Major']) + 1
                    if propertyDesc.find('Critical') != -1:
                        uiError_Obj['Critical'] = int(uiError_Obj['Critical']) + 1 
                    if propertyDesc.find('Enhancement') != -1:
                        uiError_Obj['Enhancement'] = int(uiError_Obj['Enhancement']) + 1
                if typeDesc == '兼容错误':
                    propertyObj = assignee_issue.raw['fields']['customfield_11401']
                    propertyDesc = propertyObj['value'].encode('utf-8')
                    if propertyDesc.find('Blocker') != -1:
                        compatibleError_Obj['Blocker'] = int(compatibleError_Obj['Blocker']) + 1
                    if propertyDesc.find('Major') != -1:
                        compatibleError_Obj['Major'] = int(compatibleError_Obj['Major']) + 1
                    if propertyDesc.find('Critical') != -1:
                        compatibleError_Obj['Critical'] = int(compatibleError_Obj['Critical']) + 1 
                    if propertyDesc.find('Enhancement') != -1:
                        compatibleError_Obj['Enhancement'] = int(compatibleError_Obj['Enhancement']) + 1
                if typeDesc == '用户体验问题/优化提升':
                    propertyObj = assignee_issue.raw['fields']['customfield_11401']
                    propertyDesc = propertyObj['value'].encode('utf-8')
                    if propertyDesc.find('Blocker') != -1:
                        user_Obj['Blocker'] = int(user_Obj['Blocker']) + 1
                    if propertyDesc.find('Major') != -1:
                        user_Obj['Major'] = int(user_Obj['Major']) + 1
                    if propertyDesc.find('Critical') != -1:
                        user_Obj['Critical'] = int(user_Obj['Critical']) + 1 
                    if propertyDesc.find('Enhancement') != -1:
                        user_Obj['Enhancement'] = int(user_Obj['Enhancement']) + 1
                if typeDesc == '接口问题':
                    propertyObj = assignee_issue.raw['fields']['customfield_11401']
                    propertyDesc = propertyObj['value'].encode('utf-8')
                    if propertyDesc.find('Blocker') != -1:
                        interface_Obj['Blocker'] = int(interface_Obj['Blocker']) + 1
                    if propertyDesc.find('Major') != -1:
                        interface_Obj['Major'] = int(interface_Obj['Major']) + 1
                    if propertyDesc.find('Critical') != -1:
                        interface_Obj['Critical'] = int(interface_Obj['Critical']) + 1 
                    if propertyDesc.find('Enhancement') != -1:
                        interface_Obj['Enhancement'] = int(interface_Obj['Enhancement']) + 1
                if typeDesc == '性能问题':
                    propertyObj = assignee_issue.raw['fields']['customfield_11401']
                    propertyDesc = propertyObj['value'].encode('utf-8')
                    if propertyDesc.find('Blocker') != -1:
                        performance_Obj['Blocker'] = int(performance_Obj['Blocker']) + 1
                    if propertyDesc.find('Major') != -1:
                        performance_Obj['Major'] = int(performance_Obj['Major']) + 1
                    if propertyDesc.find('Critical') != -1:
                        performance_Obj['Critical'] = int(performance_Obj['Critical']) + 1 
                    if propertyDesc.find('Enhancement') != -1:
                        performance_Obj['Enhancement'] = int(performance_Obj['Enhancement']) + 1
                if typeDesc == '安全问题':
                    propertyObj = assignee_issue.raw['fields']['customfield_11401']
                    propertyDesc = propertyObj['value'].encode('utf-8')
                    if propertyDesc.find('Blocker') != -1:
                        security_Obj['Blocker'] = int(security_Obj['Blocker']) + 1
                    if propertyDesc.find('Major') != -1:
                        security_Obj['Major'] = int(security_Obj['Major']) + 1
                    if propertyDesc.find('Critical') != -1:
                        security_Obj['Critical'] = int(security_Obj['Critical']) + 1 
                    if propertyDesc.find('Enhancement') != -1:
                        security_Obj['Enhancement'] = int(security_Obj['Enhancement']) + 1
                if typeDesc == '环境问题':
                    propertyObj = assignee_issue.raw['fields']['customfield_11401']
                    propertyDesc = propertyObj['value'].encode('utf-8')
                    if propertyDesc.find('Blocker') != -1:
                        environment_Obj['Blocker'] = int(environment_Obj['Blocker']) + 1
                    if propertyDesc.find('Major') != -1:
                        environment_Obj['Major'] = int(environment_Obj['Major']) + 1
                    if propertyDesc.find('Critical') != -1:
                        environment_Obj['Critical'] = int(environment_Obj['Critical']) + 1 
                    if propertyDesc.find('Enhancement') != -1:
                        environment_Obj['Enhancement'] = int(environment_Obj['Enhancement']) + 1

        
        # 添加统计列表
        issueObjList.append(function_miss_Obj)
        issueObjList.append(system_logicError_Obj)
        issueObjList.append(system_checkError_Obj)
        issueObjList.append(uiError_Obj)
        issueObjList.append(compatibleError_Obj)
        issueObjList.append(user_Obj)
        issueObjList.append(interface_Obj)
        issueObjList.append(performance_Obj)
        issueObjList.append(security_Obj)
        issueObjList.append(environment_Obj)
        assigneeObj['summary'] = issueObjList
        key = str(len(assignee_issues)) + '_' + assignee
        summaryList[key] = assigneeObj
    
    summaryList = OrderedDict(sorted(summaryList.items(), key=lambda x: x[1]['totalCount'],reverse=True))
    # sortKeyList = sorted(summaryList, key=lambda x: (summaryList[x]['totalCount'], summaryList[x]['totalCount']),reverse=True)
    print json.dumps(summaryList)
    return summaryList

# 修改Template
def initTemplate(templateFileName,saveFileName):
    templateFile = open(templateFileName,'r')
    templateContent = templateFile.readlines()
    templateFile.close()

    # 插入JS
    jsIndex = 0
    for i in range(0,len(templateContent)):
        if templateContent[i].find('</head>') != -1:
            jsIndex = i
            break
    baseJSFile = open('./baseJS','r')
    baseJSContent = baseJSFile.readlines()
    baseJSFile.close()
    baseJSConentStr = "".join(baseJSContent)
    templateContent.insert(jsIndex-1,baseJSConentStr)
    
    # 插入HTML
    baseHTMLFile = open('./baseHTML','r')
    baseHTMLContent = baseHTMLFile.readlines()
    baseHTMLContentStr = "".join(baseHTMLContent)
    htmlIndex = 0
    for i in range(0,len(templateContent)):
        if templateContent[i].find('</body>') != -1:
            htmlIndex = i
            break
    templateContent.insert(htmlIndex-1,baseHTMLContentStr)
    templateContentStr = "".join(templateContent)

    saveFile = open(saveFileName, "w")
    saveFile.write(templateContentStr)
    saveFile.close()
    

# 写入Template生成HTML
def writeTemplate(jiraID):
    summaryList = getSummary(jiraID)
    templateName = ''
    saveName = jiraID + '.html'
    index = 0
    for i in summaryList:
        if index == 0 :
            templateName = 'Template.html'
        else:
            templateName = saveName
        index = index + 1
        initTemplate(templateName,saveName)

        summaryObj = (summaryList[i]) 
        erp = summaryObj['name']
        totalCount = summaryObj['totalCount']
        
        issueList = summaryObj['summary']

        # 初始化变量
        global projectName
        function_Blocker_Count = 0
        function_Critical_Count = 0
        function_Major_Count = 0
        function_Enhancement_Count = 0
        function_Total = 0
        logic_Blocker_Count = 0
        logic_Critical_Count = 0
        logic_Major_Count = 0
        logic_Enhancement_Count = 0
        logic_Total = 0
        check_Blocker_Count = 0
        check_Critical_Count = 0
        check_Major_Count = 0
        check_Enhancement_Count = 0
        check_Total = 0
        ui_Blocker_Count = 0
        ui_Critical_Count = 0
        ui_Major_Count = 0
        ui_Enhancement_Count = 0
        ui_Total = 0
        com_Blocker_Count = 0
        com_Critical_Count = 0
        com_Major_Count = 0
        com_Enhancement_Count = 0
        com_Total = 0
        user_Blocker_Count = 0
        user_Critical_Count = 0
        user_Major_Count = 0
        user_Enhancement_Count = 0
        user_Total = 0
        api_Blocker_Count = 0
        api_Critical_Count = 0
        api_Major_Count = 0
        api_Enhancement_Count = 0
        api_Total = 0
        pef_Blocker_Count = 0
        pef_Critical_Count = 0
        pef_Major_Count = 0
        pef_Enhancement_Count = 0
        per_Total = 0
        sec_Blocker_Count = 0
        sec_Critical_Count = 0
        sec_Major_Count = 0
        sec_Enhancement_Count = 0
        sec_Total = 0
        env_Blocker_Count = 0
        env_Critical_Count = 0
        env_Major_Count = 0
        env_Enhancement_Count = 0
        env_Total = 0

        for issueObj in issueList:
            issueType = issueObj['type']
            if issueType == "功能遗漏":
                function_Blocker_Count = int(issueObj['Blocker'])
                function_Critical_Count = int(issueObj['Critical'])
                function_Major_Count = int(issueObj['Major'])
                function_Enhancement_Count = int(issueObj['Enhancement'])
                function_Total = function_Blocker_Count + function_Critical_Count + function_Major_Count + function_Enhancement_Count
            if issueType == "程序逻辑错误":
                logic_Blocker_Count = int(issueObj['Blocker'])
                logic_Critical_Count = int(issueObj['Critical'])
                logic_Major_Count = int(issueObj['Major'])
                logic_Enhancement_Count = int(issueObj['Enhancement'])
                logic_Total = logic_Blocker_Count + logic_Critical_Count + logic_Major_Count + logic_Enhancement_Count
            if issueType == "程序校验错误":
                check_Blocker_Count = int(issueObj['Blocker'])
                check_Critical_Count = int(issueObj['Critical'])
                check_Major_Count = int(issueObj['Major'])
                check_Enhancement_Count = int(issueObj['Enhancement'])
                check_Total = check_Blocker_Count + check_Critical_Count + check_Major_Count + check_Enhancement_Count
            if issueType == "界面错误":
                ui_Blocker_Count = int(issueObj['Blocker'])
                ui_Critical_Count = int(issueObj['Critical'])
                ui_Major_Count = int(issueObj['Major'])
                ui_Enhancement_Count = int(issueObj['Enhancement'])
                ui_Total = ui_Blocker_Count + ui_Critical_Count + ui_Major_Count + ui_Enhancement_Count
            if issueType == "兼容错误":
                com_Blocker_Count = int(issueObj['Blocker'])
                com_Critical_Count = int(issueObj['Critical'])
                com_Major_Count = int(issueObj['Major'])
                com_Enhancement_Count = int(issueObj['Enhancement'])
                com_Total = com_Blocker_Count + com_Critical_Count + com_Major_Count + com_Enhancement_Count
            if issueType == "用户体验问题/优化提升":
                user_Blocker_Count = int(issueObj['Blocker'])
                user_Critical_Count = int(issueObj['Critical'])
                user_Major_Count = int(issueObj['Major'])
                user_Enhancement_Count = int(issueObj['Enhancement'])
                user_Total = user_Blocker_Count + user_Critical_Count + user_Major_Count + user_Enhancement_Count
            if issueType == "接口问题":
                api_Blocker_Count = int(issueObj['Blocker'])
                api_Critical_Count = int(issueObj['Critical'])
                api_Major_Count = int(issueObj['Major'])
                api_Enhancement_Count = int(issueObj['Enhancement'])
                api_Total = api_Blocker_Count + api_Critical_Count + api_Major_Count + api_Enhancement_Count
            if issueType == "接口问题":
                api_Blocker_Count = int(issueObj['Blocker'])
                api_Critical_Count = int(issueObj['Critical'])
                api_Major_Count = int(issueObj['Major'])
                api_Enhancement_Count = int(issueObj['Enhancement'])
                api_Total = api_Blocker_Count + api_Critical_Count + api_Major_Count + api_Enhancement_Count
            if issueType == "性能问题":
                pef_Blocker_Count = int(issueObj['Blocker'])
                pef_Critical_Count = int(issueObj['Critical'])
                pef_Major_Count = int(issueObj['Major'])
                pef_Enhancement_Count = int(issueObj['Enhancement'])
                pef_Total = pef_Blocker_Count + pef_Critical_Count + pef_Major_Count + pef_Enhancement_Count
            if issueType == "安全问题":
                sec_Blocker_Count = int(issueObj['Blocker'])
                sec_Critical_Count = int(issueObj['Critical'])
                sec_Major_Count = int(issueObj['Major'])
                sec_Enhancement_Count = int(issueObj['Enhancement'])
                sec_Total = sec_Blocker_Count + sec_Critical_Count + sec_Major_Count + sec_Enhancement_Count
            if issueType == "环境问题":
                env_Blocker_Count = int(issueObj['Blocker'])
                env_Critical_Count = int(issueObj['Critical'])
                env_Major_Count = int(issueObj['Major'])
                env_Enhancement_Count = int(issueObj['Enhancement'])
                env_Total = env_Blocker_Count + env_Critical_Count + env_Major_Count + env_Enhancement_Count
            
        # 加载模板文件
        env = Environment(
            loader=FileSystemLoader('./'),
            autoescape=select_autoescape(['html','xml'])
        ) 
        template = env.get_template(saveName)
        result = template.render(
            erp = erp,
            title = projectName,
            total_count = totalCount,
            function_total = function_Total,
            function_blocker_count = function_Blocker_Count,
            function_critical_count = function_Critical_Count,
            function_major_count = function_Major_Count,
            function_enhancement_count = function_Enhancement_Count,
            logic_total = logic_Total,
            logic_blocker_count = logic_Blocker_Count,
            logic_critical_count = logic_Critical_Count,
            logic_major_count = logic_Major_Count,
            logic_enhancement_count = logic_Enhancement_Count,
            check_total = check_Total,
            check_blocker_count = check_Blocker_Count,
            check_critical_count = check_Critical_Count,
            check_major_count = check_Major_Count,
            check_enhancement_count = check_Enhancement_Count,
            ui_total = ui_Total,
            ui_blocker_count = ui_Blocker_Count,
            ui_critical_count = ui_Critical_Count,
            ui_major_count = ui_Major_Count,
            ui_enhancement_count = ui_Enhancement_Count,
            com_total = com_Total,
            com_blocker_count = com_Blocker_Count,
            com_critical_count = com_Critical_Count,
            com_major_count = com_Major_Count,
            com_enhancement_count = com_Enhancement_Count,
            user_total = user_Total,
            user_blocker_count = user_Blocker_Count,
            user_critical_count = user_Critical_Count,
            user_major_count = user_Major_Count,
            user_enhancement_count = user_Enhancement_Count,
            api_total = api_Total,
            api_blocker_count = api_Blocker_Count,
            api_critical_count = api_Critical_Count,
            api_major_count = api_Major_Count,
            api_enhancement_count = api_Enhancement_Count,
            per_total = pef_Total,
            per_blocker_count = pef_Blocker_Count,
            per_critical_count = pef_Critical_Count,
            per_major_count = pef_Major_Count,
            per_enhancement_count = pef_Enhancement_Count,
            sec_total = sec_Total,
            sec_blocker_count = sec_Blocker_Count,
            sec_critical_count = sec_Critical_Count,
            sec_major_count = sec_Major_Count,
            sec_enhancement_count = sec_Enhancement_Count,
            env_total = env_Total,
            env_blocker_count = env_Blocker_Count,
            env_critical_count = env_Critical_Count,
            env_major_count = env_Major_Count,
            env_enhancement_count = env_Enhancement_Count
        )
        resultFile = open(saveName,'w')
        resultFile.write(result)
        resultFile.close()



def start():
    idFile = open('./jiraID.txt','r')
    for line in idFile.readlines():
        line = line.rstrip()
        writeTemplate(line)
    

start()
